//导入mysql模块
var mysql = require('mysql');
var dbconfig = require('./dbConfig');
var usersql = require('./usersql');
var Code = require('./checkCode');
//使用dbconfig.js 配置创建一个mysql连接池
var pool = mysql.createPool(dbconfig.mysql);

function outprint(result){
    console.log('--------------------------SELECT----------------------------');
    console.log(result);
    console.log('------------------------------------------------------------\n\n');  
};




//查 query
function getUserQueryALL(callback){
    
    pool.getConnection(function(err,connection){
        //建立连接
        connection.query(usersql.queryAll,function(err,result){
            connection.release();
            callback(Code(result,err));
        })
    })
}

function getUserByPhone(phone,callback){
    pool.getConnection(function(err,connection){
        if(phone==undefined)return;
        connection.query(usersql.getUserByPhone,phone,function(err,result){
            connection.release();
            callback(Code(result,err));
        })
    })
}

//增 insert
function addUser(params,callback){
    pool.getConnection(function(err,connection){
        var type;
        if(params.phone==undefined || params.address==undefined)return;
        //建立连接
        connection.query(usersql.insert,[params.phone,params.address],function(err,result){
            connection.release();
            callback(Code(result,err));
        })
    })
};

//删 delete
function delUser(phone,callback){
    pool.getConnection(function(err,connection){
        //处理数据
        if(phone==undefined)return;
        //建立连接
        connection.query(usersql.delUserByPhone,phone,function(err,result){
            connection.release();
            callback(Code(result,err));
        })
    })
};

//改 update
function updateUserAddress(params,callback){
    pool.getConnection(function(err,connection){
        //处理数据
        if(params.phone==undefined || params.address ==undefined)return;
        //建立连接
        connection.query(usersql.updateUserAddressByPhone,[params.address,params.phone],function(err,result){
            connection.release();
            callback(Code(result,err));
        })
    })
}

module.exports={getUserQueryALL,getUserByPhone,addUser,delUser,updateUserAddress};